package com.xb.ai.repository;

import cn.hutool.core.bean.BeanUtil;

import com.xb.ai.entity.po.Chat;
import com.xb.ai.entity.vo.ChatVo;
import com.xb.ai.service.IChatService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class InMysqlChatHistoryRepository implements ChatHistoryRepository {

    @Resource
    private IChatService chatService;

    @Override
    public void save(Long chatId, Long userId, String messageTitle) {
        Chat chat = chatService.lambdaQuery()
                .eq(Chat::getChatId, chatId)
                .one();
        // 数据不存在 说明是新对话
        if (chat == null) {
            chat = new Chat();
            chat.setChatId(chatId);
            chat.setUserId(userId);
            chat.setMessageTitle(messageTitle);
            chatService.save(chat);
        } // 可能存在bug
    }

    @Override
    public List<ChatVo> getChatList(Long userId) {
        List<Chat> chatList = chatService.lambdaQuery()
                .eq(Chat::getUserId, userId)
                .list();
        return BeanUtil.copyToList(chatList, ChatVo.class);
    }


    @Override
    public boolean delete(Long chatId, Long userId) {
        return chatService.lambdaUpdate()
                .eq(Chat::getChatId, chatId)
                .eq(Chat::getUserId, userId)
                .remove();
    }

}
